package com.robusta.cityuate.fragments;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.robusta.cityuate.R;
import com.robusta.cityuate.activities.ReservationActivity;
import com.robusta.cityuate.activities.UserProfileActivity;
import com.robusta.cityuate.adapters.TimeSlotsAdapter;
import com.robusta.cityuate.base.ViewType;
import com.robusta.cityuate.base.ViewType.Type;
import com.robusta.cityuate.objects.Offering;
import com.robusta.cityuate.objects.Reservation;
import com.robusta.cityuate.objects.TimeSlot;
import com.robusta.cityuate.objects.User;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.utils.ConnectionUtils;

public class TimeSlotsListFragment extends SherlockListFragment {

	public interface OfferingCarrier{
		public Offering getOffering();
		public ViewType.Type getOwnershipType();
	}
	private LinearLayout fragmentView;
	private ProgressBar progressBar;
	private LinearLayout listPart;
	private Button retryBtn;
	private Type ownershipType;
	private Context mContext;
	private TimeSlotsAdapter adapter;
	private Offering offer;
	private String DEL_TAG=TimeSlotsListFragment.class.getName();

	private CityuateBroadCastReceiver deleteReceiver = new CityuateBroadCastReceiver() {

		@Override
		public void onCancel() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

		@Override
		public void onSuccess() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

		@Override
		public void onFailure() {
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext,
					ConnectionUtils.getExtra(mContext, DEL_TAG),
					Toast.LENGTH_LONG).show();
			ConnectionUtils.clearConnection(mContext, DEL_TAG);
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		fragmentView = (LinearLayout) inflater.inflate(
				R.layout.offerings_list_fragment_view, container, false);
		progressBar = (ProgressBar) fragmentView
				.findViewById(R.id.spots_loading);
		listPart = (LinearLayout) fragmentView.findViewById(R.id.list_part);
		// show retry button
		retryBtn = (Button) fragmentView.findViewById(R.id.retry);

		retryBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// fragmentView.removeView(retryBtn);
//				retryBtn.setVisibility(View.GONE);
//				ConnectionUtils.clearConnection(mContext, TAG);
//				getOfferings();

			}
		});

		return fragmentView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		this.ownershipType = ((OfferingCarrier) getActivity()).getOwnershipType();
		mContext=getActivity();
		this.adapter = new TimeSlotsAdapter(mContext, ownershipType);
		setListAdapter(adapter);
		offer=((OfferingCarrier) getActivity()).getOffering();
		adapter.updateEnteries(offer.getTimeSlots());

	}

	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		registerForContextMenu(getListView());
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		
		mContext.registerReceiver(deleteReceiver, new IntentFilter(DEL_TAG));
		progressBar.setVisibility(View.GONE);
		listPart.setVisibility(View.VISIBLE);
		
		if (ConnectionUtils.isConnecting(mContext, DEL_TAG))
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(true);
		
		if (ConnectionUtils.wasConnected(mContext, DEL_TAG))
			// connection was successful
			if (ConnectionUtils.isResultSuccessful(mContext, DEL_TAG))
				deleteReceiver.onSuccess();
			else
				deleteReceiver.onFailure();

	}

	@Override
	public void onPause() {
		super.onPause();
		mContext.unregisterReceiver(deleteReceiver);

		if (!ConnectionUtils.isConnecting(mContext, DEL_TAG))
			ConnectionUtils.clearConnection(mContext, DEL_TAG);

	}


	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		TimeSlot timeSlot=(TimeSlot)adapter.getItem(info.position);
		android.view.MenuInflater mInflater=getActivity().getMenuInflater();
		mInflater.inflate(R.menu.time_slots_context_menu, menu);
		
		if(!timeSlot.isReserved())
			menu.findItem(R.id.cancel).setEnabled(false);
		
	}
	
	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		Reservation res = ((TimeSlot) adapter.getItem(info.position)).getReservation();
		switch (item.getItemId()) {
		case R.id.cancel:
			confirmDeleteReservation(res);
			break;

		default:
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	/**
	 * 
	 * @param res
	 */
	private void confirmDeleteReservation(final Reservation res) {
		// Use the Builder class for convenient dialog construction
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(getString(R.string.cancel_res_confirm));
		builder.setMessage(R.string.cancel_res_confirm_msg)
				.setPositiveButton(R.string.delete,
						new DialogInterface.OnClickListener() {
						
							public void onClick(DialogInterface dialog, int id) {

						getSherlockActivity().setSupportProgressBarIndeterminateVisibility(true);
								res.delete(mContext, DEL_TAG);
							}
						}).setNegativeButton(R.string.cancel, null);

		builder.show();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		TimeSlot timeSlot=(TimeSlot) l.getAdapter().getItem(position);
		if (timeSlot.isReserved()) {

			if (ownershipType == Type.OWNER) {
				Intent reserver = new Intent(mContext,
						UserProfileActivity.class);
				reserver.putExtra(User.USER, timeSlot.getReservation()
						.getReserver());
				mContext.startActivity(reserver);
			}

		} else {
			Intent reserve = new Intent(mContext,
					ReservationActivity.class);
			reserve.putExtra(TimeSlot.TIME_SLOT, timeSlot);
			mContext.startActivity(reserve);
		}

	}
	
}
